// lib/screens/user_posts/user_posts_screen.dart
import 'package:flutter/material.dart';
import 'package:flutter_bluebell/api/post_api.dart';
import 'package:flutter_bluebell/models/post.dart';
import 'package:flutter_bluebell/routes/app_routes.dart'; // 用于导航到帖子详情

class UserPostsScreen extends StatefulWidget {


  const UserPostsScreen({super.key});

  @override
  State<UserPostsScreen> createState() => _UserPostsScreenState();
}

class _UserPostsScreenState extends State<UserPostsScreen> {
  final PostApi _postApi = PostApi();
  List<Post> _userPosts = [];
  bool _isLoading = true;
  String? _errorMessage;

  @override
  void initState() {
    super.initState();
    _fetchUserPosts();
  }

  // --- 获取用户帖子列表 ---
  Future<void> _fetchUserPosts() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });
    try {
      final response = await _postApi.getUserPosts();
      if (response.code == 1000 && response.data != null) {
        setState(() {
          _userPosts = response.data!;
        });
      } else {
        setState(() {
          _errorMessage = response.msg;
        });
      }
    } catch (e) {
      setState(() {
        _errorMessage = e.toString();
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  // --- 删除帖子函数 ---
  Future<void> _deletePost(String postId) async {
    // 弹出确认对话框
    final bool? confirm = await showDialog<bool>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('确认删除'),
          content: const Text('你确定要删除这条帖子吗？此操作不可撤销。'),
          actions: <Widget>[
            TextButton(
              onPressed: () => Navigator.of(context).pop(false), // 取消
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () => Navigator.of(context).pop(true), // 确认
              child: const Text('删除', style: TextStyle(color: Colors.red)),
            ),
          ],
        );
      },
    );

    // 如果用户确认删除
    if (confirm == true) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('正在删除帖子...')),
      );
      try {
        await _postApi.deleteUserPost(postId);
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('帖子删除成功！')),
        );
        // 删除成功后，刷新列表以移除已删除的帖子
        _fetchUserPosts();
      } catch (e) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('删除帖子失败: ${e.toString()}')),
        );
        print('删除帖子失败: $e'); // 打印详细错误信息
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('我的发布'), // 页面标题
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator()) // 加载中
          : _errorMessage != null
          ? Center(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                '加载帖子失败: $_errorMessage',
                textAlign: TextAlign.center,
                style: const TextStyle(color: Colors.red),
              ),
              const SizedBox(height: 20),
              ElevatedButton(
                onPressed: _fetchUserPosts, // 点击重试按钮
                child: const Text('重试'),
              ),
            ],
          ),
        ),
      )
          : _userPosts.isEmpty
          ? const Center(child: Text('你还没有发布任何帖子。')) // 空数据提示
          : RefreshIndicator(
        onRefresh: _fetchUserPosts, // 支持下拉刷新
        child: ListView.builder(
          itemCount: _userPosts.length,
          itemBuilder: (context, index) {
            final post = _userPosts[index];
            return Card(
              margin: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
              elevation: 2,
              child:
              ListTile(

                title: Text(post.title, style: const TextStyle(fontWeight: FontWeight.bold)),
                subtitle: Text(
                  post.content,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
                // 右侧添加删除按钮
                trailing: IconButton(
                  icon: const Icon(Icons.delete, color: Colors.red),
                  onPressed: () => _deletePost(post.postId), // 调用删除函数
                ),
                onTap: () {
                  // 点击跳转到帖子详情页
                  Navigator.pushNamed(
                    context,
                    AppRoutes.postDetailScreen,
                    arguments: post.postId,
                  );
                },
              ),
            );
          },
        ),
      ),
    );
  }
}